<?php
/**
 * oscshop2 B2C电子商务系统
 *
 * ==========================================================================
 * @link      http://www.oscshop.cn/
 * @copyright Copyright (c) 2015-2017 oscshop.cn. 
 * @license   http://www.oscshop.cn/license.html License
 * ==========================================================================
 *
 * @author    
 *
 * 余额   api接口
 * 2017-03-11
 */
namespace osc\common\service;
use think\Db;
class Predeposit{
	
	//余额充值
	function recharge($uid,$pay_code,$money){
		
		if(!is_numeric($money)){				
			return array('error'=>'请输入数字');
		}			
		//负数
		if($money<0){
			return array('error'=>'充值金额不能是负数');
		}
		if($money<config('predeposit_num')){
			return array('error'=>'充值金额最少为'.config('predeposit_num').'元');
		}
		$data['uid']=$uid;
		$username=member('username');
		$data['username']=empty($username)?member('nickname'):$username;
		$data['order_num_alias']=build_order_no();
		$data['money']=$money;
		$data['description']='余额充值';
		$data['prefix']=1;
		$data['payment_code']=$pay_code;
		$data['pay_status']=0;
		$data['creat_time']=time();
		
		$id=Db::name('predeposit')->insert($data,false,true);
		
		return array(
			'pay_order_no'=>$data['order_num_alias'],
			'subject'=>'余额充值'.$money,
			'pay_total'=>$money,
			'id'=>$id
		);
	}
	//更新充值订单
	function update_recharge_order($id,$uid,$money){
		Db::name('predeposit')->where('p_id',$id)->update(array('pay_status'=>1,'pay_time'=>time()));
		Db::name('member')->where('uid',$uid)->setInc('predeposit',$money);
	}
	
	private function validate($data){
		
		$uid=$data['uid'];
		
		if(!$uid){
			return ['error'=>'请先登录'];
		}
		
		$cart=osc_cart();
		
		if(!$cart->count_cart_total($uid,$data['type'])) {	
			return ['error'=>'您的购物车没有商品'];	
		}
		
		$city_id=$data['city_id'];		
		
		$shipping=$cart->has_shipping($uid,$data['type']);
		//配送验证
		if(isset($shipping['error'])){			
			return ['error'=>$shipping['error']];
		}
		
		//需要配送的
		if($shipping){
			if($city_id==''){
				return ['error'=>'请选择收货地址'];
			}
		}
		
		// 验证商品数量		
		$cart_list=Db::name('cart')->where(array('uid'=>$uid,'type'=>$data['type']))->select();
		
		foreach ($cart_list as $k => $v) {
			
			$param['option']=json_decode($v['goods_option'], true);
			$param['goods_id']=$v['goods_id'];
			$param['quantity']=$v['quantity'];
			
			//判断商品是否存在，验证最小起订量   		
	   		if($error=$cart->check_minimum($param)){   			
	   			return $error;			
	   		}			
					
			//验证商品数量和必选项
			if($error=$cart->check_quantity($param)){			
				return $error;
			}
			
		}
		return [
			'uid'=>$uid,
			'city_id'=>$city_id,
			'shipping'=>$shipping
		];
	}
	//计算商品总价(默认类型为普通商品)
	function calcul_total($uid,$city_id,$type,$shipping_method){
		$goods=osc_cart()->get_all_goods($uid,$type);
		$total_all_price=0;
		$weight = 0;
		if(!empty($goods)){
			foreach ($goods as $k => $v) {
				$total_all_price+=$v['total'];
				if ($v['shipping']&&$v['free_shipping']==0) {
					$weight += osc_weight()->convert($v['weight'], $v['weight_class_id'],config('weight_id'));
				}
			}
		}
		
		//总价达到免运费额度
		if($total_all_price>=config('free_shipping')){
			$weight=0;
		}
		
		$t=osc_transport()->calc_transport($shipping_method,$weight,$city_id);

		return array(
			'total'=>$t['price']+$total_all_price,
			'weight'=>$weight
		);

	}
	
	//余额支付
	function pay($data){
		if(request()->isPost()){
			$uid=is_login();
						
			$result=$this->validate($data);
			
			if(isset($result['error'])){
				return $result;
			}


			$calcul=$this->calcul_total($result['uid'],$result['city_id'],$data['type'],$data['shipping_method']);



			//需要配送的
			if($result['shipping']){								
				$weight =$calcul['weight'];
				$order['shipping_method']=$data['shipping_method'];		
			}else{
				$weight=0;
				$order['shipping_method']='';
			}

			if($calcul['total']>6000)
			{
				return array('error'=>'每次最大消费额度为6000元宝！');
			}

			$ye=$data['jilin_bean'];
			if($ye<$calcul['total']){
				return array('error'=>'金豆不足,剩余'.$ye);
			}


			$username = session('username');

			$user1 = Db::name('member')->where('username',$username)->find();



			if(is_null($data['m_total_buy']) )
			{
				$data['m_total_buy'] = 0;
			}

			$total = $user1['m_total_buy'] + $calcul['total'];


//			$config_max = Db::name('config')->where('name','max_consume')->find();
			
			//var_dump($order);

			$order['shipping_address_id']=$data['address_id']; 
			
			$order['payment_method']='jilin_bean';
			$order['weight']=$weight;
			$order['shipping_city_id']=$result['city_id'];
			$order['comment']=$data['comment'];
			$order['uid']=$result['uid'];
			$order['username']=$data['username'];

			//开始事务
			try
			{
				Db::startTrans();

				//写入订单
				$order=osc_order()->add_order('jilin_bean',$order);
				//清空购物车
				osc_order()->clear_cart($order['uid']);
				//更新订单，订单历史，积分，商品数量
				osc_order()->update_order($order['order_id']);

				$username=$data['username'];

				$username=empty($username)?member('nickname'):$username;

				//推荐奖
				//$r= osc_service('common','Sttl')->recomm_bonus($calcul['total'],$order['order_id']);

				//更新余额
				$user_order_info = array(
						'uid'=>$result['uid'],
						'username'=>$username,
						'order_id'=>$order['order_id'],
						'order_num_alias'=>$order['pay_order_no'],
						'total'=>$calcul['total']
				);
				$this->update_predeposit($user_order_info);

				//结束事务
				Db::commit();

			} catch (\Exception $e) {

				Db::rollbacke();
			}

			
		}
	}
	
	//更新余额
	function update_predeposit($order){

		$user = Db::name('member')->where('uid',$order['uid'])->find();
		$befor = (int)$user['jilin_bean'];
		$after = (int)$user['jilin_bean'] - $order['total'];
		Db::name('predeposit')->insert(array(
				'uid'=>$order['uid'],
				'username'=>$order['username'],
				'order_id'=>$order['order_id'],
				'order_num_alias'=>$order['order_num_alias'],
				'money'=>$order['total'],
				'description'=>'购买商品,购买前元宝数量'.$befor.' 购买后元宝数量'.$after,
				'prefix'=>2,
				'creat_time'=>time(),
				'pay_time'=>time(),
				'pay_status'=>1
			));

		Db::name('member')->where('uid',$order['uid'])->dec('jilin_bean',$order['total'])->update();
	}

}